package com.woniu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author Rain
 * @Description :
 * @date 2022/09/05 17:12
 */
public class JWTUtils {
    private static final String SECRET_KEY="woniu";
    private static final long EXPIRES = 30 *1000 *60;//30分钟

    public static String sign(String username,String password) {
        long exTime = System.currentTimeMillis() + EXPIRES;
        return JWT.create().withClaim("username",username)
                .withExpiresAt(new Date(exTime))
                .sign(Algorithm.HMAC256(username+password+SECRET_KEY));

    }

    public static String getUsername(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("username").asString();
    }

    public static void verify(String token, String username, String password){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(username+password+SECRET_KEY)).withClaim("username", username).build();
        verifier.verify(token);
    }
}
